package com.yhb.myshop.web.admin.service.impl;

import com.yhb.myshop.commons.entity.BaseResult;
import com.yhb.myshop.domain.BaseEntity;
import com.yhb.myshop.web.admin.dao.BaseDao;
import com.yhb.myshop.web.admin.service.BaseService;
import com.yhb.myshop.web.admin.web.validator.EntityValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;

import java.util.Date;

public abstract class BaseServiceImpl<T extends BaseEntity,D extends BaseDao<T>> implements BaseService<T> {
    @Autowired
    protected D dao;

    @Override
    public BaseResult create(T model) {
        BaseResult baseResult = EntityValidator.validate(model);
        if (!baseResult.isSuccess()) {
            return baseResult;
        }
        model.setCreated(new Date());
        model.setUpdated(new Date());
        return getBaseResult(dao.create(model),"新增失败");
    }

    public T getById(int id) {
        return dao.getById(id);
    }

    public BaseResult update(T model)
    {
        BaseResult baseResult = EntityValidator.validate(model);
        if (!baseResult.isSuccess()) {
            return baseResult;
        }
        model.setUpdated(new Date());
        return getBaseResult(dao.update(model),"更新失败");
    }

    public BaseResult delete(int id) {
        return getBaseResult(dao.delete(id),"删除失败");
    }

    private BaseResult getBaseResult(int row,String error){
        BaseResult baseResult = BaseResult.success();

        if(row<=0){
            baseResult=BaseResult.fail(error);
        }
        return baseResult;
    }
}
